package com.mai4j.maiadmin.setup;

import com.littlenb.snowflake.sequence.IdGenerator;
import com.littlenb.snowflake.support.MillisIdGeneratorFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.JavaMigration;
import org.reflections.Reflections;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

@Slf4j
public class Helper {

    private static final IdGenerator generator = new MillisIdGeneratorFactory(1609430400000L).create(1);
    /**
     * a-Z0-9
     */
    private static final String ALL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    /**
     * 获取Java代码编译的Migrations
     *
     * @param packageNames packageNames
     * @return JavaMigrations
     * @throws Exception Exception
     */
    public static JavaMigration[] getJavaMigrations(String... packageNames) throws Exception {
        Set<JavaMigration> javaMigrations = new HashSet<>();
        for (String packageName : packageNames) {
            Reflections reflections = new Reflections(packageName);
            Set<Class<? extends BaseJavaMigration>> subTypes = reflections.getSubTypesOf(BaseJavaMigration.class);
            for (Class<? extends BaseJavaMigration> subType : subTypes) {
                javaMigrations.add(subType.getDeclaredConstructor().newInstance());
            }
        }
        return javaMigrations.toArray(new JavaMigration[]{});
    }


    /**
     * @return id
     */
    public static long next() {
        return generator.nextId();
    }

    /**
     * 随机生成指定长度的字符串
     *
     * @param length length
     * @return String
     */
    public static String rand(int length) {
        StringBuilder token = new StringBuilder();
        int max = ALL.length() - 1;
        for (int i = 0; i < length; i++) token.append(ALL.toCharArray()[new Random().nextInt(max)]);
        return token.toString();
    }

    /**
     * 生成密码
     *
     * @param password password
     * @param salt     salt
     * @return password
     */
    public static String password(String password, String salt) {
        return DigestUtils.sha1Hex(salt + DigestUtils.sha1Hex(salt + DigestUtils.sha1Hex(password)));
    }
}
